//  This file is part of Swordbible - http://www.swordwarrior.net
//  Copyright (C) 2003-2009 Manu Mital mital.manu@gmail.com

//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2, or (at your option)
//  any later version.

//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software Foundation,
//  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.


// MainFrm.cpp : implementation of the CMainFrame class
//

#include <stdafx.h>
#include "SwordBible.h"
#include "MainFrm.h"
#include "BibleTree.h"
#include "BibleForm.h"
#include ".\mainfrm.h"
#include "Remove.h"
#include "SwordBibleView.h"
#include "CrossLinksMgr.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


//////////////////////////////////////////////////////////////////////////////////

CVerseLists* CMainFrame::m_pModelessVL = NULL;


// CMainFrame

IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
	ON_WM_CREATE()
	ON_COMMAND(ID_TOP_MAX, OnTopMax)
	ON_COMMAND(ID_BOTTOM_MAX, OnBottomMax)
	ON_COMMAND(ID_NORMAL, OnNormal)
	ON_WM_SIZE()
	ON_COMMAND(ID_DELETE_BOOKMARK, OnDeleteBookmark)
	ON_COMMAND(ID_ADD_BOOKMARK, OnAddBookmark)
	ON_COMMAND_RANGE(ID_BOOKMARK_STRING + 3,ID_BOOKMARK_STRING + 2 + MAXBOOKMARKS, OnSubMenuBookMarks)
	ON_COMMAND(ID_BIBLEPAGE_SEARCH, OnMenuBiblepageSearch)
	ON_COMMAND(ID_BOTTOM_SEARCH, OnBottomSearch)
	ON_COMMAND(ID_BIBLE_DISPLAY,OnMainDisplay)
	ON_COMMAND(ID_BOTTOM_DISPLAY,OnBottomDisplay)
	ON_COMMAND(ID_VIEW_DEVOTIONAL, OnViewDevotional)
	ON_COMMAND(ID_VERSELISTS, OnVerseLists)
  ON_COMMAND(ID_SCRIPTURECHALLENGE, OnScriptureChallenge)
  ON_COMMAND(ID_HELP, OnHelp)
	ON_COMMAND(ID_WEB, OnWeb)
	ON_COMMAND(ID_INSTALLMGR, OnInstallMgr)
	ON_COMMAND(ID_PRAYERREQUEST, OnPrayerrequest)

	ON_UPDATE_COMMAND_UI(ID_VIEW_QUICKVERSE_TOOLBAR, OnUpdateControlBarMenu)
	ON_COMMAND_EX(ID_VIEW_QUICKVERSE_TOOLBAR, OnBarCheck)


	// lemma tags
	ON_COMMAND(ID_LEMMA, OnLemma)
	ON_UPDATE_COMMAND_UI(ID_LEMMA, OnUpdateLemma)

	// morph tags
	ON_COMMAND(ID_MORPH, OnMorph)
	ON_UPDATE_COMMAND_UI(ID_MORPH, OnUpdateMorph)
	
	// footnotes
	ON_COMMAND(ID_FOOTNOTES, OnFootnotes)
	ON_UPDATE_COMMAND_UI(ID_FOOTNOTES, OnUpdateFootnotes)
	
	// cross-references
	ON_COMMAND(ID_CROSSREF, OnCrossref)
	ON_UPDATE_COMMAND_UI(ID_CROSSREF, OnUpdateCrossref)
	
	// preverse heading
	ON_COMMAND(ID_HEADINGS, OnHeading)
	ON_UPDATE_COMMAND_UI(ID_HEADINGS, OnUpdateHeading)

		// preverse heading
	ON_COMMAND(ID_REDCHRIST, OnRed)
	ON_UPDATE_COMMAND_UI(ID_REDCHRIST, OnUpdateRed)

	ON_MESSAGE(WM_SHOW_DEVOTIONAL, OnShowDevotional)
	
  ON_COMMAND(ID_CROSSLINKSMGR, OnCrossLinksManager)

   ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, OnToolTipNotify)
   ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, OnToolTipNotify)

	ON_WM_DESTROY()

	ON_COMMAND(ID_BIBLE_PRINT, &CMainFrame::OnMainBiblePrint)
	ON_COMMAND(ID_BIBLE_COPY, &CMainFrame::OnMainBibleCopy)
	ON_COMMAND(ID_BIBLE_SELECTALL, &CMainFrame::OnMainBibleSelectall)
	ON_COMMAND(ID_BIBLEPAGE_COPYMANAGER, &CMainFrame::OnBiblepageCopymanager)
	ON_COMMAND(ID_BIBLE_ZOOMTEXT, &CMainFrame::OnMainBibleZoomtext)
 // ON_COMMAND(ID_BIBLE_RTL, &CMainFrame::OnMainBibleRTL)
	ON_COMMAND(ID_BIBLE_SPLITVIEW, &CMainFrame::OnBibleSplitview)
	ON_COMMAND(ID_BIBLE_PREVIOUSCHAPTER, &CMainFrame::OnMainBiblePrevious)
	ON_COMMAND(ID_BIBLE_NEXTCHAPTER, &CMainFrame::OnMainBibleNext)
 // ON_UPDATE_COMMAND_UI(ID_BIBLE_RTL, &CMainFrame::OnUpdateBibleRTL)
	ON_UPDATE_COMMAND_UI(ID_BIBLE_ZOOMTEXT, &CMainFrame::OnUpdateBibleZoom)
  ON_COMMAND(ID_BIBLE_INFORMATION, &CMainFrame::OnMainBibleInfo)
	ON_COMMAND(ID_COMMENTARY_COPY, &CMainFrame::OnCommentaryCopy)
	ON_COMMAND(ID_COMMENTARY_SELECTALL, &CMainFrame::OnMFCommentarySelectall)
	ON_COMMAND(ID_COMMENTARY_ZOOMTEXT, &CMainFrame::OnMFCommentaryZoomtext)
	ON_UPDATE_COMMAND_UI(ID_COMMENTARY_ZOOMTEXT, &CMainFrame::OnMFUpdateCommentaryZoom)
	ON_COMMAND(ID_COMMENTARY_PREVIOUSCHAPTER, &CMainFrame::OnMFCommentaryPrevious)
	ON_COMMAND(ID_COMMENTARY_NEXTCHAPTER, &CMainFrame::OnMFCommentaryNext)
  ON_COMMAND(ID_COMMENTARY_INFORMATION, &CMainFrame::OnMFCommentaryInfo)
	ON_COMMAND(ID_COMMENTARY_PRINT, &CMainFrame::OnMFCommentaryPrint)
	ON_COMMAND(ID_COMMENTARY_SYNCHRONIZE, &CMainFrame::OnMFCommentarySynch)
	ON_UPDATE_COMMAND_UI(ID_COMMENTARY_SYNCHRONIZE, &CMainFrame::OnUpdateMFCommentarySynch)
	ON_UPDATE_COMMAND_UI(ID_BIBLE_SPLITVIEW, &CMainFrame::OnUpdateBibleSplitview)
	ON_COMMAND(ID_NOTES_PREVIOUSCHAPTER, &CMainFrame::OnNotesPrevious)
	ON_COMMAND(ID_NOTES_NEXTCHAPTER, &CMainFrame::OnNotesNext)
	ON_COMMAND(ID_NOTES_SAVE, &CMainFrame::OnNotesSave)
	ON_COMMAND(ID_NOTES_PRINT, &CMainFrame::OnNotesPrint)
	ON_COMMAND(ID_NOTES_SYNCHRONIZE, &CMainFrame::OnNotesSynchronize)
    ON_COMMAND(ID_NOTES_INSERTLINK, &CMainFrame::OnNotesInsertLink)
	ON_COMMAND(ID_NOTES_CUT, &CMainFrame::OnNotesCut)
	ON_COMMAND(ID_NOTES_COPY, &CMainFrame::OnNotesCopy)
	ON_COMMAND(ID_NOTES_PASTE, &CMainFrame::OnNotesPaste)
	ON_COMMAND(ID_NOTES_BOLD, &CMainFrame::OnNotesBold)
	ON_UPDATE_COMMAND_UI(ID_NOTES_BOLD, &CMainFrame::OnUpdateNotesBold)
	ON_COMMAND(ID_NOTES_ITALIC, &CMainFrame::OnNotesItalic)
	ON_UPDATE_COMMAND_UI(ID_NOTES_ITALIC, &CMainFrame::OnUpdateNotesItalic)
	ON_UPDATE_COMMAND_UI(ID_NOTES_UNDERLINE, &CMainFrame::OnUpdateNotesUnderline)
	ON_COMMAND(ID_NOTES_LEFTALIGN, &CMainFrame::OnNotesLeftalign)
	ON_UPDATE_COMMAND_UI(ID_NOTES_LEFTALIGN, &CMainFrame::OnUpdateNotesLeftalign)
	ON_COMMAND(ID_NOTES_CENTERALIGN, &CMainFrame::OnNotesCenteralign)
	ON_UPDATE_COMMAND_UI(ID_NOTES_CENTERALIGN, &CMainFrame::OnUpdateNotesCenteralign)
	ON_COMMAND(ID_NOTES_RIGHTALIGN, &CMainFrame::OnNotesRightalign)
	ON_UPDATE_COMMAND_UI(ID_NOTES_RIGHTALIGN, &CMainFrame::OnUpdateNotesRightalign)
	ON_COMMAND(ID_NOTES_INSERTBULLETS, &CMainFrame::OnNotesInsertbullets)
	ON_UPDATE_COMMAND_UI(ID_NOTES_SYNCHRONIZE, &CMainFrame::OnUpdateNotesSynchronize)
	ON_COMMAND(ID_NOTES_UNDERLINE, &CMainFrame::OnNotesUnderline)
	
	ON_COMMAND(ID_DICTIONARY_PRINT, &CMainFrame::OnDictionaryPrint)
	ON_COMMAND(ID_DICTIONARY_COPY, &CMainFrame::OnDictionaryCopy)
	ON_COMMAND(ID_DICTIONARY_SELECTALL, &CMainFrame::OnDictionarySelectall)
	ON_COMMAND(ID_DICTIONARY_DISPLAY, &CMainFrame::OnBottomleftDisplay)
	ON_COMMAND(ID_DICTIONARY_PREVIOUSENTRY, &CMainFrame::OnDictionaryPrevious)
	ON_COMMAND(ID_DICTIONARY_NEXTENTRY, &CMainFrame::OnDictionaryNext)
  ON_COMMAND(ID_DICTIONARY_INFORMATION, &CMainFrame::OnDictionaryInfo)
	ON_COMMAND(ID_DICTIONARY_ZOOMTEXT, &CMainFrame::OnDictionaryZoomtext)
	ON_UPDATE_COMMAND_UI(ID_DICTIONARY_ZOOMTEXT, &CMainFrame::OnUpdateDictionaryZoom)

	ON_COMMAND(ID_GENBOOKS_PRINT, &CMainFrame::OnGenBooksPrint)
	ON_COMMAND(ID_GENBOOKS_COPY, &CMainFrame::OnGenBooksCopy)
	ON_COMMAND(ID_GENBOOKS_SELECTALL, &CMainFrame::OnGenBooksSelectall)
	ON_COMMAND(ID_GENBOOKS_DISPLAY, &CMainFrame::OnGenBooksDisplay)
	ON_COMMAND(ID_GENBOOKS_PREVIOUS, &CMainFrame::OnGenBooksPrevious)
	ON_COMMAND(ID_GENBOOKS_NEXT, &CMainFrame::OnGenBooksNext)
  ON_COMMAND(ID_GENBOOKS_INFORMATION, &CMainFrame::OnGenBooksInfo)
	ON_COMMAND(ID_GENBOOKS_ZOOMTEXT, &CMainFrame::OnGenBooksZoomtext)
	ON_UPDATE_COMMAND_UI(ID_GENBOOKS_ZOOMTEXT, &CMainFrame::OnUpdateGenBooksZoom)
	
		
	
	ON_COMMAND(ID_OPTIONS_REMEMBERLAST, &CMainFrame::OnOptionsRememberlast)
	ON_UPDATE_COMMAND_UI(ID_OPTIONS_REMEMBERLAST, &CMainFrame::OnUpdateRememberlast)
	ON_COMMAND(ID_OPTIONS_DEVOTIONAL, &CMainFrame::OnOptionsDevotional)
	ON_UPDATE_COMMAND_UI(ID_OPTIONS_DEVOTIONAL, &CMainFrame::OnUpdateOptionsDevotional)
	ON_WM_CLOSE()

  ON_CBN_DROPDOWN(IDC_COMBO_QUICKVERSE, OnQuickVerseDropDown)
	ON_COMMAND(ID_QUICKVERSE_GO, OnQuickVerseGo)

	
	END_MESSAGE_MAP()

static UINT indicators[] =
{
	ID_SEPARATOR,           // status line indicator
	ID_INDICATOR_CAPS,
	ID_INDICATOR_NUM,
	ID_INDICATOR_SCRL,
};


// CMainFrame construction/destruction

CMainFrame::CMainFrame()
{
	m_bPreview = FALSE;
	m_pModeless = NULL;
	m_pModelessVL = NULL;

}

CMainFrame::~CMainFrame()
{
	

	
}


int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
		return -1;
	
	if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT , WS_CHILD |
        WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS |
         CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||

       !m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
   {
      TRACE0("Failed to create toolbar\n");
      return -1;      // fail to create
   }


	if (!m_wndQuickVerseBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
	| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC, CRect(0, 0, 0, 0), ID_VIEW_QUICKVERSE_TOOLBAR) ||
	!m_wndQuickVerseBar.LoadToolBar(IDR_MAINFRAME_QUICKVERSE))
	{
	TRACE0("Failed to create toolbar\n");
	return -1; // fail to create
	}

	// create the combo box for the quick verse toolbar
	CRect rect;
	m_wndQuickVerseBar.GetItemRect( m_wndQuickVerseBar.CommandToIndex(ID_DUMMY1), rect);
	rect.right += (rect.Width() * 6); // Using 7 dummy buttons for space.
	rect.top =  3;      //(((rect.Height() - GetSystemMetrics(SM_CYMENU)) + 1) / 2); // + 3;
	rect.bottom += 260;
	rect.left += 5;

	// Create the combo box!
	if(!QuickVerseCombo.Create(CBS_DROPDOWN | WS_VISIBLE | WS_CHILD, rect, &m_wndQuickVerseBar, IDC_COMBO_QUICKVERSE) )
	{
	TRACE("Failed to create combo-box\n");
	return false;
	}

	
	pFont = new CFont();  //<--- deleted in the destructor
	pFont->CreatePointFont(90,_T("Arial"));
	QuickVerseCombo.SetFont(pFont);
	

	if (!m_wndStatusBar.Create(this) )
	{
		TRACE0("Failed to create status bar\n");
		return -1;      // fail to create
	}


		//load the application icon
	HICON icon = ::AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	SetIcon(icon, TRUE);

	m_wndToolBar.LoadTCToolBar(32, IDB_TOOLBAR_MAINFRAME,IDB_TOOLBAR_MAINFRAME,
                             IDB_TOOLBAR_MAINFRAME, RGB(254,128,254));
	
	m_wndQuickVerseBar.LoadTCToolBar(24, IDB_BITMAP_QUICKVERSE,IDB_BITMAP_QUICKVERSE,
                             IDB_BITMAP_QUICKVERSE, RGB(255,128,255));


   m_bibleDlg.instance = AFX_MAINBIBLE;
  m_comDlg.instance = AFX_BOTTOM;
  m_dictDlg.instance = AFX_BOTTOMLEFT;

  m_dictDlg.SetBarStyle(m_treeDlg.GetBarStyle() |CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC);
  
   if (!m_treeDlg.Create(_T("Navigation"), this, CSize(120, 200),  TRUE, 123))
  {
    TRACE0("Failed to create tree navigation\n");
    return -1;
    // fail to create
   }  

   m_treeDlg.SetBarStyle(m_treeDlg.GetBarStyle() |CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC);



  if (!m_bibleDlg.Create(_T("Bibles"), this, CSize(500, 200),  TRUE, 124))
  {
    TRACE0("Failed to create bible dialog\n");
    return -1;
    // fail to create
   }  

  m_bibleDlg.SetBarStyle(m_bibleDlg.GetBarStyle() |CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC);

  if (!m_comDlg.Create(_T("Commentaries"), this, CSize(400, 200),  TRUE, 125))
  {
    TRACE0("Failed to create bible dialog\n");
    return -1;
  }  

  m_comDlg.SetBarStyle(m_bibleDlg.GetBarStyle() |CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC);
  
  if (!m_dictDlg.Create(_T("Lexicons / Dictionaries"), this, CSize(400, 500),  TRUE, 126))
  {
    TRACE0("Failed to create bible dialog\n");
    return -1;
   }  
  
  
  EnableDocking(CBRS_ALIGN_ANY);

	m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
	m_wndQuickVerseBar.EnableDocking(CBRS_ALIGN_ANY);	
	m_bibleDlg.EnableDocking(CBRS_ALIGN_ANY);
  m_comDlg.EnableDocking(CBRS_ALIGN_ANY);
  m_dictDlg.EnableDocking(CBRS_ALIGN_ANY);
	m_treeDlg.EnableDocking(CBRS_ALIGN_ANY);
	
  OnNormal();

	// load the bookmarks from the registry
	LoadBookmarks();

	//Load the verse history in the quick verse toolbar
	LoadQuickHistory();

	return 0;
}


BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
	if( !CFrameWnd::PreCreateWindow(cs) )
		return FALSE;
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs

	cs.style &= ~FWS_ADDTOTITLE;

	return TRUE;
}

BOOL CMainFrame::PreTranslateMessage(MSG* pMsg)
{
	if( (pMsg->message == WM_KEYDOWN) 
		&& (pMsg->wParam == VK_RETURN) 
		&&	 GetFocus()->GetSafeHwnd() == QuickVerseCombo.GetFocus()->GetSafeHwnd() )
	{
		OnQuickVerseGo();
		return TRUE;
	}

	return CFrameWnd::PreTranslateMessage(pMsg);
}


// CMainFrame diagnostics

#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
	CFrameWnd::AssertValid();
}

void CMainFrame::Dump(CDumpContext& dc) const
{
	CFrameWnd::Dump(dc);
}

#endif //_DEBUG

void CMainFrame::OnTopMax()
{
	 //adjust the visibility of windows
	if(m_wndToolBar.IsVisible() == FALSE) SendMessage(WM_COMMAND,ID_VIEW_TOOLBAR);
	if(m_wndQuickVerseBar.IsVisible() == FALSE) SendMessage(WM_COMMAND,ID_VIEW_QUICKVERSE_TOOLBAR);
	if(m_bibleDlg.IsVisible() == FALSE) ShowControlBar(&m_bibleDlg, TRUE,FALSE);
	if(m_comDlg.IsVisible() == TRUE) ShowControlBar(&m_comDlg,  FALSE, FALSE);
	if(m_dictDlg.IsVisible() == TRUE) ShowControlBar(&m_dictDlg,  FALSE, FALSE);
	if(m_treeDlg.IsVisible() == FALSE) ShowControlBar(&m_treeDlg,  TRUE, FALSE); 

  CRect rc;
	DockControlBar(&m_wndToolBar,AFX_IDW_DOCKBAR_TOP);
	RecalcLayout(TRUE);
	m_wndToolBar.GetWindowRect(rc);
    
	// position the quick verse toolbar next to the main toolbar
	rc.OffsetRect(1,0);
	DockControlBar(&m_wndQuickVerseBar,AFX_IDW_DOCKBAR_TOP,rc);
	RecalcLayout(TRUE);
  
  CRect totalSize;
  GetWindowRect(&totalSize);
  UINT w = totalSize.Width();
  UINT h = totalSize.Height() - 48;

 
  m_wndToolBar.GetWindowRect(&rc);
  rc.OffsetRect(0,1);
  DockControlBar(&m_treeDlg, AFX_IDW_DOCKBAR_LEFT, rc);
  RecalcLayout(TRUE);
  
  m_treeDlg.GetWindowRect(&rc);
  rc.OffsetRect(1,0);
  DockControlBar(&m_bibleDlg, AFX_IDW_DOCKBAR_RIGHT, rc);   
  RecalcLayout(TRUE);

  m_treeDlg.SetSize(110, h);
  m_bibleDlg.SetSize( w - 110, h);
  DockControlBar(&m_bibleDlg, AFX_IDW_DOCKBAR_LEFT);

  
}

void CMainFrame::OnBottomMax()
{
 	 //adjust the visibility of windows
	if(m_wndToolBar.IsVisible() == FALSE) SendMessage(WM_COMMAND,ID_VIEW_TOOLBAR);
	if(m_wndQuickVerseBar.IsVisible() == FALSE) SendMessage(WM_COMMAND,ID_VIEW_QUICKVERSE_TOOLBAR);
	if(m_bibleDlg.IsVisible() == TRUE) ShowControlBar(&m_bibleDlg, FALSE,FALSE);
	if(m_comDlg.IsVisible() == FALSE) ShowControlBar(&m_comDlg,  TRUE, FALSE);
	if(m_dictDlg.IsVisible() == TRUE) ShowControlBar(&m_dictDlg,  FALSE, FALSE);
	if(m_treeDlg.IsVisible() == FALSE) ShowControlBar(&m_treeDlg,  TRUE, FALSE); 

  CRect rc;
	DockControlBar(&m_wndToolBar,AFX_IDW_DOCKBAR_TOP);
	RecalcLayout(TRUE);
	m_wndToolBar.GetWindowRect(rc);
    
	// position the quick verse toolbar next to the main toolbar
	rc.OffsetRect(1,0);
	DockControlBar(&m_wndQuickVerseBar,AFX_IDW_DOCKBAR_TOP,rc);
	RecalcLayout(TRUE);
  
  CRect totalSize;
  GetWindowRect(&totalSize);
  UINT w = totalSize.Width();
  UINT h = totalSize.Height() - 48;

 
  m_wndToolBar.GetWindowRect(&rc);
  rc.OffsetRect(0,1);
  DockControlBar(&m_treeDlg, AFX_IDW_DOCKBAR_LEFT, rc);
  RecalcLayout(TRUE);
  
  m_treeDlg.GetWindowRect(&rc);
  rc.OffsetRect(1,0);
  DockControlBar(&m_comDlg, AFX_IDW_DOCKBAR_RIGHT, rc);   
  RecalcLayout(TRUE);

  m_treeDlg.SetSize(110, h);
  m_comDlg.SetSize( w - 110, h);
  DockControlBar(&m_comDlg, AFX_IDW_DOCKBAR_LEFT);


}

void CMainFrame::OnNormal()
{
	// show all the windows that are invisible
	if(m_wndToolBar.IsVisible() == FALSE) SendMessage(WM_COMMAND,ID_VIEW_TOOLBAR);
	if(m_wndQuickVerseBar.IsVisible() == FALSE) SendMessage(WM_COMMAND,ID_VIEW_QUICKVERSE_TOOLBAR);
	if(m_bibleDlg.IsVisible() == FALSE) ShowControlBar(&m_bibleDlg, TRUE,FALSE);
	if(m_comDlg.IsVisible() == FALSE) ShowControlBar(&m_comDlg,  TRUE, FALSE);
	if(m_dictDlg.IsVisible() == FALSE) ShowControlBar(&m_dictDlg,  TRUE, FALSE);
	if(m_treeDlg.IsVisible() == FALSE) ShowControlBar(&m_treeDlg,  TRUE, FALSE);

 CRect totalSize;
 GetWindowRect(&totalSize);
  UINT w = totalSize.Width() - 2;
  UINT h = totalSize.Height() - 48;

 	
  CRect rc;
	DockControlBar(&m_wndToolBar,AFX_IDW_DOCKBAR_TOP);
	RecalcLayout(TRUE);
	m_wndToolBar.GetWindowRect(&rc);
  rc.OffsetRect(1,0);
	DockControlBar(&m_wndQuickVerseBar,AFX_IDW_DOCKBAR_TOP,rc);
 
  m_wndToolBar.GetWindowRect(&rc);
  rc.OffsetRect(0,1);
  DockControlBar(&m_treeDlg, AFX_IDW_DOCKBAR_LEFT, rc);
  RecalcLayout(TRUE);
  
  m_treeDlg.GetWindowRect(&rc);
  rc.OffsetRect(1,0);
  DockControlBar(&m_comDlg, AFX_IDW_DOCKBAR_BOTTOM,rc); 
  RecalcLayout(TRUE);

  m_comDlg.GetWindowRect(&rc);
  rc.OffsetRect(0,-1);
  DockControlBar(&m_dictDlg, AFX_IDW_DOCKBAR_RIGHT, rc); 
  RecalcLayout(TRUE);
  

  m_treeDlg.SetSize(110, h/2);
  m_comDlg.SetSize(w,h/2);
  m_bibleDlg.SetSize((w - 110)/2, h/2);
  m_dictDlg.SetSize((w-110)/2, h/2);
    
  DockControlBar(&m_bibleDlg, AFX_IDW_DOCKBAR_LEFT, rc); 
  RecalcLayout(TRUE);

  
}



// CMainFrame message handlers


void CMainFrame::OnSize(UINT nType, int cx, int cy)
{
	CFrameWnd::OnSize(nType, cx, cy);
}

void CMainFrame::OnDeleteBookmark()
{
	CRemove dlg;
	dlg.icon = _T("file");
	dlg.type = _T("multiple");
	dlg.arr.RemoveAll();

	
	 CString listStr = AfxGetApp()->GetProfileString(_T("BOOKMARKS"), _T("list"), _T(""));
	 sword::VerseKey vk;
	 sword::ListKey lk = vk.ParseVerseList((CStringA) listStr, vk , TRUE);


	 for(lk= sword::TOP; !lk.Error(); lk++)   dlg.arr.Add( (CString) lk );

	

	if( dlg.DoModal() == IDOK)
	{
		AfxGetApp() ->WriteProfileString(_T("BOOKMARKS"), _T("list"), dlg.modList);
		LoadBookmarks();

	}



}


// add a new bookmark
void CMainFrame::OnAddBookmark()
{
	CMenu *pMainMenu = GetMenu();
	CMenu *pSubMenu = pMainMenu->GetSubMenu(bmmi); 


	CString BookMark;  // this is the bookmark that needs to be added
	BookMark.Format(_T("%s %d:%d"),CSwordBibleDoc::key.getBookAbbrev(),CSwordBibleDoc::Chapter(), CSwordBibleDoc::Verse());
	sword::SWKey bmKey = (CStringA) BookMark;
	sword::SWKey existing;

	int numSubMenuEntries = pSubMenu ->GetMenuItemCount();


	// make sure that the bookmark to be added does not already exist
	for(int  i = 0; i < numSubMenuEntries; i++)
    {
		CString subMenuChild;
		pSubMenu->GetMenuString(i,subMenuChild,MF_BYPOSITION);
		existing = (CStringA) subMenuChild;

		if(existing == bmKey)
		return;                          // return if bookmark already exists


	}

		// write the new item in the registry
	    CString list = AfxGetApp()->GetProfileString(_T("BOOKMARKS"), _T("list"), _T(""));
		list = list + _T(";") + BookMark;
		AfxGetApp() ->WriteProfileString(_T("BOOKMARKS"), _T("list"), list);

		// Add bookmark to the mainframe menu
		int zero_based_pos = ( pSubMenu->GetMenuItemCount() );
		pSubMenu ->AppendMenu(MF_STRING,ID_BOOKMARK_STRING + zero_based_pos, BookMark);
	

}


// this function is called when a user clicks on a bookmark from the 
// main menu
void CMainFrame::OnSubMenuBookMarks(UINT nID)
{

	CMenu *pMainMenu = GetMenu();

	CMenu *pSubMenu = pMainMenu->GetSubMenu(bmmi); // Bookmark is submenu 8

	int id = int(nID)- int(ID_BOOKMARK_STRING);

	CString bookmarkStr;

    pSubMenu->GetMenuString(id, bookmarkStr, MF_BYPOSITION);

	CSwordBibleDoc::key = (CStringA) bookmarkStr;


   //SendMessageToDescendants(WM_TREE_SETSEL,0,0);  <-- don't call this if we want to highlight bookmarked verse

	 /* the new key has been set. Change the display in the bible, and if synchronize is TRUE, change the 
       display in the notes/commentary */

	CBiblePage::ActiveMainFrameCommand = _T("ShowChapter");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND, 0,0);

	if(CSwordBibleDoc::notesSynch)
	{
	CNotesPage::ActiveMainFrameCommand = ("BibleSynch");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
	}

	if(CSwordBibleDoc::bottomSynch)
	{
	CBottomPage::ActiveMainFrameCommand = _T("BibleSynch");
	SendMessageToDescendants(ID_COMMENTARY_COMMAND,0,0);
	}

	// highlight the verse in the bible window
	CBiblePage::ActiveMainFrameCommand = _T("highlight");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND,0,0);
}


// load the bookmarks from the registry into the mainframe  menu
void CMainFrame::LoadBookmarks(void)
{
	
	CMenu *pMainMenu = GetMenu();
	CMenu *pSubMenu = pMainMenu->GetSubMenu(bmmi); // Bookmark is submenu 8

	int numSubMenuEntries = pSubMenu ->GetMenuItemCount();

	int i = numSubMenuEntries - 1;

	while(i > 2) pSubMenu->RemoveMenu(i--, MF_BYPOSITION);  // remove all existing bookmarks

	// get bookmarks from the registry and add them	
	 CString listStr = AfxGetApp()->GetProfileString(_T("BOOKMARKS"), _T("list"), _T(""));
	 sword::VerseKey vk;
	 sword::ListKey lk = vk.ParseVerseList((CStringA) listStr, vk , TRUE);

	
	 for(lk= sword::TOP; !lk.Error(); lk++)
	 {
		 i++;
		 pSubMenu ->AppendMenu(MF_STRING,ID_BOOKMARK_STRING + i, (CString) lk  );
	 }


}

void CMainFrame::OnViewDevotional()
{
	 // Display the dialog box
    if (!m_pModeless)
        m_pModeless = new CDevotional;

   if (!::IsWindow(m_pModeless->GetSafeHwnd()))
        m_pModeless->Create(IDD_DEVOTIONAL, this);

    m_pModeless->ShowWindow(SW_SHOW); 

}


void CMainFrame::OnVerseLists()
{
	 // Display the dialog box
    if (!m_pModelessVL)
       m_pModelessVL= new CVerseLists;

   if (!::IsWindow(m_pModelessVL->GetSafeHwnd()))
       m_pModelessVL->Create(IDD_VERSELISTS, this);

    m_pModelessVL->ShowWindow(SW_SHOW);

}

void CMainFrame::OnScriptureChallenge()
{

  CBibleSheet::DisableStrongMorph();
 
   // Display the dialog box
    CHangman dlg;
    dlg.DoModal();

     CBibleSheet::RestoreStrongMorph();



}


LRESULT CMainFrame::OnShowDevotional(WPARAM wParam, LPARAM lParam)
{
	// TODO: Add your command handler code here

OnViewDevotional();

	return 0L;
}



void CMainFrame::OnWeb()
{
		ShellExecute(NULL, _T("open"), _T("http://swordwarrior.net/?page_id=71"),
		NULL, NULL, SW_SHOWNORMAL);

}

void CMainFrame::OnHelp()
{
  CString path;
  CBibleSheet::GetAppDirectory(path);
 
#if defined VERSION_PORTABLE
  path.Replace(_T("\\App\\SwordBible"),  _T("\\Other\\Help\\SBHelp.chm"));
#else 
  path += _T("\\SBHelp.chm");
#endif


  ::HtmlHelp(this->m_hWnd,path , HH_DISPLAY_TOPIC, NULL);
}

void CMainFrame::OnInstallMgr()
{
	
		STARTUPINFO si;
PROCESS_INFORMATION pi;
memset(&pi, 0, sizeof(pi));
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);

 
 

#if defined VERSION_PORTABLE
  CString path;
  CBibleSheet::GetAppDirectory(path);
  path.Replace(_T("\\App\\SwordBible"),  _T(""));

  CString configFilePath = path + _T("\\Data\\installMgr\\InstallMgr.conf");
 CString defConfigFilePath = path +  _T("\\App\\DefaultData\\installMgr\\InstallMgr.conf");


 // copy the install manager config file from the default folder
  if ( (GetFileAttributes(configFilePath) == -1)   &&  
                  !(GetFileAttributes(defConfigFilePath) == -1)     ) {

    CString dir = path + _T("\\Data\\installMgr");
	  CreateDirectory(dir, NULL);
    ::CopyFile(defConfigFilePath, configFilePath, TRUE); //copy file 
   
  }


  CString data = path + _T("\\Data");
  CString mods_d = data + _T("\\mods.d");

  CreateDirectory(mods_d, NULL); // nothing happens if this dir already exists

  CreateProcess(0, _T("InstallManager.exe") ,  0, 0, 0, 0, 0, data, &si, &pi);
#else
CreateProcess(0, _T("InstallManager.exe") ,
  0, 0, 0, 0, 0, 0, &si, &pi);
#endif

}


void CMainFrame::OnPrayerrequest()
{
		ShellExecute(NULL, _T("open"), _T("mailto:dwellingplace77@hotmail.com?SUBJECT=Prayer Request"),
		NULL, NULL, SW_SHOWNORMAL);
}

// turn the strong's numbers on or off
void CMainFrame::OnLemma()
{
	CSwordBibleDoc::lemma_tags = !(CSwordBibleDoc::lemma_tags);

	// write setting to the registry
	AfxGetApp()->WriteProfileInt(_T("Tags"), _T("lemma_tags"), CSwordBibleDoc::lemma_tags);

	
  CBibleSheet::OnToggleTags();

	// redisplay 
 	CBiblePage::ActiveMainFrameCommand = _T("ShowChapter");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND, 0,0);

	
	
}

void CMainFrame::OnUpdateLemma(CCmdUI * pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::lemma_tags);

}


void CMainFrame::OnMorph()

{
	CSwordBibleDoc::morph_tags = !(CSwordBibleDoc::morph_tags);

	// write setting to the registry
	AfxGetApp()->WriteProfileInt(_T("Tags"), _T("morph_tags"), CSwordBibleDoc::morph_tags);

	
  CBibleSheet::OnToggleTags();

	// redisplay 
 	CBiblePage::ActiveMainFrameCommand = _T("ShowChapter");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND, 0,0);
	
}

void CMainFrame::OnUpdateMorph(CCmdUI * pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::morph_tags);

}

void CMainFrame::OnFootnotes()
{
	CSwordBibleDoc::fn_tags = !(CSwordBibleDoc::fn_tags);

	// write setting to the registry
	AfxGetApp()->WriteProfileInt(_T("Tags"),_T("fn_tags"), CSwordBibleDoc::fn_tags);

	
  CBibleSheet::OnToggleTags();

	// redisplay 
 	CBiblePage::ActiveMainFrameCommand = _T("ShowChapter");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND, 0,0);
}

void CMainFrame::OnUpdateFootnotes(CCmdUI * pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::fn_tags);

}


void CMainFrame::OnCrossref()
{
	CSwordBibleDoc::crossref_tags = !(CSwordBibleDoc::crossref_tags);

	// write setting to the registry
	AfxGetApp()->WriteProfileInt(_T("Tags"),_T("crossref_tags"), CSwordBibleDoc::crossref_tags);

	CBibleSheet::OnToggleTags();

	// redisplay 
 	CBiblePage::ActiveMainFrameCommand = _T("ShowChapter");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND, 0,0);
}

void CMainFrame::OnUpdateCrossref(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::crossref_tags);
	
}

void CMainFrame::OnHeading()
{
	CSwordBibleDoc::heading_tags = !(CSwordBibleDoc::heading_tags);

	// write setting to the registry
	AfxGetApp()->WriteProfileInt(_T("Tags"),_T("heading_tags"), CSwordBibleDoc::heading_tags);

	
  CBibleSheet::OnToggleTags();

// redisplay 
 	CBiblePage::ActiveMainFrameCommand = _T("ShowChapter");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND, 0,0);
}

void CMainFrame::OnUpdateHeading(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::heading_tags);
	
}

void CMainFrame::OnRed()
{
	CSwordBibleDoc::redchrist_tags = !(CSwordBibleDoc::redchrist_tags);

	// write setting to the registry
	AfxGetApp()->WriteProfileInt(_T("Tags"),_T("redchrist_tags"), CSwordBibleDoc::redchrist_tags);

	
  CBibleSheet::OnToggleTags();

	// redisplay 
 	CBiblePage::ActiveMainFrameCommand = _T("ShowChapter");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND, 0,0);
}

void CMainFrame::OnUpdateRed(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::redchrist_tags);
	
}

void CMainFrame::OnCrossLinksManager()
{
  CCrossLinksMgr dlg;  
  dlg.DoModal();

}



BOOL CMainFrame::OnToolTipNotify(UINT id, NMHDR *pNMHDR,   LRESULT *pResult)
{
	
   ASSERT(pNMHDR->code == TTN_NEEDTEXTA || pNMHDR->code == TTN_NEEDTEXTW);

     // to be thorough we will need to handle UNICODE versions of the message also !!
     TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
     TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
     TCHAR szFullText[512];
     CString strTipText;
     UINT nID = pNMHDR->idFrom;

     if (pNMHDR->code == TTN_NEEDTEXTA && (pTTTA->uFlags & TTF_IDISHWND) ||
         pNMHDR->code == TTN_NEEDTEXTW && (pTTTW->uFlags & TTF_IDISHWND))
     {
          // idFrom is actually the HWND of the tool 
          nID = ::GetDlgCtrlID((HWND)nID);
     }

     if (nID != 0) // will be zero on a separator
     {
          AfxLoadString(nID, szFullText);
          strTipText=szFullText;

#ifndef _UNICODE
          if (pNMHDR->code == TTN_NEEDTEXTA)
          {
               lstrcpyn(pTTTA->szText, strTipText, sizeof(pTTTA->szText));
          }
          else
          {
               _mbstowcsz(pTTTW->szText, strTipText, sizeof(pTTTW->szText));
          }
#else
          if (pNMHDR->code == TTN_NEEDTEXTA)
          {
               _wcstombsz(pTTTA->szText, strTipText,sizeof(pTTTA->szText));
          }
          else
          {
               lstrcpyn(pTTTW->szText, strTipText, sizeof(pTTTW->szText));
          }
#endif

          *pResult = 0;

          // bring the tooltip window above other popup windows
          ::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, 0, 0, 0, 0,SWP_NOACTIVATE|
               SWP_NOSIZE|SWP_NOMOVE|SWP_NOOWNERZORDER); return TRUE;
     }

     return FALSE;
}

void CMainFrame::OnClose()
{
	 if (m_bPreview)
        {		
			AfxGetMainWnd()->SendMessage(WM_COMMAND,AFX_ID_PREVIEW_CLOSE);
			return;
        }
	 
	 CFrameWnd::OnClose();

}

void CMainFrame::OnSetPreviewMode(BOOL bPreview, CPrintPreviewState* pState)
{
	m_bPreview = bPreview;
    CFrameWnd::OnSetPreviewMode(bPreview, pState);
}

// save the window placement on program exit
void CMainFrame::SavePosition()
{
   WINDOWPLACEMENT pwp;
   pwp.length = sizeof(pwp);
   GetWindowPlacement(&pwp);
   CString strBuffer;  
   strBuffer.Format("%i %i %i %i %i %i %i %i %i %i",
     pwp.flags, pwp.showCmd,  
     pwp.ptMinPosition.x , pwp.ptMinPosition.y ,  
     pwp.ptMaxPosition.x , pwp.ptMaxPosition.y , 
     pwp.rcNormalPosition.left , pwp.rcNormalPosition.top ,    
     pwp.rcNormalPosition.right , pwp.rcNormalPosition.bottom);  
   
   AfxGetApp()->WriteProfileString("General","WindowPosition",strBuffer); 
	
}

// restore the window placement on program startup
void CMainFrame::RestorePosition()
{
  WINDOWPLACEMENT pwp;
  CString strBuffer = AfxGetApp()->GetProfileString("General","WindowPosition"); 
  int cRead = _stscanf(strBuffer,"%i %i %i %i %i %i %i %i %i %i", 
    &pwp.flags,&pwp.showCmd,   
    &pwp.ptMinPosition.x , &pwp.ptMinPosition.y ,  
    &pwp.ptMaxPosition.x , &pwp.ptMaxPosition.y ,  
    &pwp.rcNormalPosition.left , &pwp.rcNormalPosition.top , 
    &pwp.rcNormalPosition.right , &pwp.rcNormalPosition.bottom);  
  
  
    if (cRead == 10)  {  
      pwp.length = sizeof(pwp); 
      SetWindowPlacement(&pwp);  
    }    
    
    UpdateWindow(); 
	

}

// On program exit, save the quick verse history (these are the latest verses
// that the user has typed in the quick verse toolbar

void CMainFrame::SaveQuickHistory()
{
		// write in the registry
	    CString list = _T("");

		int count = CSwordBibleDoc::VerseHistory.GetCount();

		if(count > MAXHISTORY) count = MAXHISTORY;

		for(int i = 0; i < count; i++)
		{
			list = list + CSwordBibleDoc::VerseHistory.GetAt(i) + _T("; ");
		}

			AfxGetApp() ->WriteProfileString(_T("QUICKVERSE"), _T("list"), list);



}

// On program startup, load the quick verse history from the registry (these are the latest verses
// that the user has typed in the quick verse toolbar
void CMainFrame::LoadQuickHistory()
{
	// get verses from the registry and add them to quick verse history array	
	 CString listStr = AfxGetApp()->GetProfileString(_T("QUICKVERSE"), _T("list"), _T(""));
	 sword::VerseKey vk;
	 sword::ListKey lk = vk.ParseVerseList((CStringA) listStr, vk , TRUE);

	 CSwordBibleDoc::VerseHistory.RemoveAll(); //empty the array
	 
	 while(QuickVerseCombo.GetCount() > 0 )   //  empty the combo box
	 QuickVerseCombo.DeleteString(0);

	 int i = 0;
	
   sword::VerseKey key;

	 for(lk= sword::TOP; !lk.Error() && i < MAXHISTORY ; lk++)
	 {
		 i++;
     key = lk;
     CSwordBibleDoc::VerseHistory.Add( (CString)key.getShortText() );
	 }


}

void CMainFrame::OnDestroy()
{
	//save window position
	 SavePosition();

	 // save quick history
	 SaveQuickHistory();

	 //save the state of the toolbars
	 CFrameWnd * pWnd = m_wndQuickVerseBar.GetDockingFrame();
	 if(pWnd->GetSafeHwnd() ) pWnd->SaveBarState(_T("QuickVerseDockState"));

	 m_bibleDlg.SaveState(_T("Bibles"));
	 m_comDlg.SaveState(_T("Commentaries"));
	 m_dictDlg.SaveState(_T("Lexicons / Dictionaries"));
	 m_treeDlg.SaveState(_T("Navigation"));

   // save the active bible key
   AfxGetApp()->WriteProfileString(_T("BiblePage"),_T("LastKey"), (CString) CSwordBibleDoc::key.getShortText() );


	 if(pFont)
	 {
		 delete pFont;
		 pFont = NULL;
	 }

	// destroy the devotional modeless dialog box 
	if (m_pModeless)
    {
       if (::IsWindow(m_pModeless->GetSafeHwnd()))
            m_pModeless->EndDialog(IDCANCEL);
        delete m_pModeless;
			
    }
	m_pModeless = NULL;

   
	   // destroy the verselists dialog box
	if (m_pModelessVL)
    {
       if (::IsWindow(m_pModelessVL->GetSafeHwnd()))
            m_pModelessVL->EndDialog(IDCANCEL);
        delete m_pModelessVL;
			
    }
	m_pModelessVL= NULL;


  
	CFrameWnd::OnDestroy();

	
}

/////////////////////////////// Messages from main frame to the bible window /////////////////////////////



void CMainFrame::OnMainBiblePrint()
{
	CBiblePage::ActiveMainFrameCommand = _T("print");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND,0,0);
}

void CMainFrame::OnMainBibleCopy()
{
	CBiblePage::ActiveMainFrameCommand = _T("copy");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND,0,0);
}

void CMainFrame::OnMainBibleSelectall()
{
	CBiblePage::ActiveMainFrameCommand = _T("selectall");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND,0,0);
}

void CMainFrame::OnBiblepageCopymanager()
{
	CBiblePage::ActiveMainFrameCommand = _T("copymgr");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND,0,0);
}
/*
void CMainFrame::OnMainBibleRTL()
{
  CBiblePage::ActiveMainFrameCommand = _T("RTL");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND,0,0);
}

void CMainFrame::OnUpdateBibleRTL(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::bibleRTL);
}
*/

void CMainFrame::OnMainDisplay()
{
	CBiblePage::ActiveMainFrameCommand = _T("display");
    SendMessageToDescendants(ID_BIBLEPAGE_COMMAND,0,0);
}


void CMainFrame::OnMainBibleZoomtext()
{
	CBiblePage::ActiveMainFrameCommand = _T("zoom");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND,0,0);
}

void CMainFrame::OnUpdateBibleZoom(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::bibleZoom);
	
}

void CMainFrame::OnMenuBiblepageSearch()
{
	CBiblePage::ActiveMainFrameCommand = _T("search");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND,0,0);
}

void CMainFrame::OnBibleSplitview()
{
	CBiblePage::ActiveMainFrameCommand = _T("split");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND,0,0);
}

void CMainFrame::OnUpdateBibleSplitview(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck( CSwordBibleDoc::bibleSplit);
}


void CMainFrame::OnMainBiblePrevious()
{
	CBiblePage::ActiveMainFrameCommand = _T("previous");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND,0,0);
}

void CMainFrame::OnMainBibleNext()
{
	CBiblePage::ActiveMainFrameCommand = _T("next");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND,0,0);
}

void CMainFrame::OnMainBibleInfo()
{
  CBiblePage::ActiveMainFrameCommand = _T("info");
  SendMessageToDescendants(ID_BIBLEPAGE_COMMAND,0,0);

}

/////////////////////////////// Messages from main frame to the commentary window /////////////////////////////


void CMainFrame::OnMFCommentaryPrint()
{
	CBottomPage::ActiveMainFrameCommand = _T("print");
	SendMessageToDescendants(ID_COMMENTARY_COMMAND,0,0);
}

void CMainFrame::OnMFCommentarySynch()
{
	CBottomPage::ActiveMainFrameCommand = _T("synch");
	SendMessageToDescendants(ID_COMMENTARY_COMMAND,0,0);
	
}

void CMainFrame::OnUpdateMFCommentarySynch(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::bottomSynch);
	
}

void CMainFrame::OnCommentaryCopy()
{
	CBottomPage::ActiveMainFrameCommand = _T("copy");
	SendMessageToDescendants(ID_COMMENTARY_COMMAND,0,0);
}

void CMainFrame::OnMFCommentarySelectall()
{
	CBottomPage::ActiveMainFrameCommand = _T("selectall");
	SendMessageToDescendants(ID_COMMENTARY_COMMAND,0,0);
}

void CMainFrame::OnBottomDisplay()
{
	CBottomPage::ActiveMainFrameCommand = _T("display");
	SendMessageToDescendants(ID_COMMENTARY_COMMAND,0,0);
}

void CMainFrame::OnMFCommentaryZoomtext()
{
	CBottomPage::ActiveMainFrameCommand = _T("zoom");
	SendMessageToDescendants(ID_COMMENTARY_COMMAND,0,0);
}

void CMainFrame::OnMFUpdateCommentaryZoom(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::bottomZoom);
}

void CMainFrame::OnBottomSearch()
{
	CBottomPage::ActiveMainFrameCommand = _T("search");
	SendMessageToDescendants(ID_COMMENTARY_COMMAND,0,0);
}

void CMainFrame::OnMFCommentaryPrevious()
{
	CBottomPage::ActiveMainFrameCommand = _T("previous");
	SendMessageToDescendants(ID_COMMENTARY_COMMAND,0,0);
}

void CMainFrame::OnMFCommentaryNext()
{
	CBottomPage::ActiveMainFrameCommand = _T("next");
	SendMessageToDescendants(ID_COMMENTARY_COMMAND,0,0);
}

void CMainFrame::OnMFCommentaryInfo()
{
	CBottomPage::ActiveMainFrameCommand = _T("info");
	SendMessageToDescendants(ID_COMMENTARY_COMMAND,0,0);
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// Messages from main frame to the notes window /////////////////////////////


void CMainFrame::OnNotesPrevious()
{
	CNotesPage::ActiveMainFrameCommand = _T("previous");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
}

void CMainFrame::OnNotesNext()
{
	CNotesPage::ActiveMainFrameCommand = _T("next");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
}

void CMainFrame::OnNotesSave()
{
	CNotesPage::ActiveMainFrameCommand = _T("save");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
}

void CMainFrame::OnNotesPrint()
{
	CNotesPage::ActiveMainFrameCommand = _T("print");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
}

void CMainFrame::OnNotesSynchronize()
{
	CNotesPage::ActiveMainFrameCommand = ("synchronize");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
}

void CMainFrame::OnNotesInsertLink()
{
	CNotesPage::ActiveMainFrameCommand = ("insertlink");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
}

void CMainFrame::OnUpdateNotesSynchronize(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::notesSynch);
}


void CMainFrame::OnNotesCut()
{
	CNotesPage::ActiveMainFrameCommand = _T("cut");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
}

void CMainFrame::OnNotesCopy()
{
	CNotesPage::ActiveMainFrameCommand = _T("copy");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
}

void CMainFrame::OnNotesPaste()
{
	CNotesPage::ActiveMainFrameCommand = _T("paste");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
}

void CMainFrame::OnNotesBold()
{
	CNotesPage::ActiveMainFrameCommand = _T("bold");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
}

void CMainFrame::OnUpdateNotesBold(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::notesBold);	
}

void CMainFrame::OnNotesItalic()
{
	CNotesPage::ActiveMainFrameCommand = _T("italic");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
}

void CMainFrame::OnUpdateNotesItalic(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::notesItalic);
}


void CMainFrame::OnNotesUnderline()
{
	CNotesPage::ActiveMainFrameCommand = _T("underline");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
}


void CMainFrame::OnUpdateNotesUnderline(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::notesUnderline);
}

void CMainFrame::OnNotesLeftalign()
{
	CNotesPage::ActiveMainFrameCommand = _T("left");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
}

void CMainFrame::OnUpdateNotesLeftalign(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::notesParaLeft);
}

void CMainFrame::OnNotesCenteralign()
{
	CNotesPage::ActiveMainFrameCommand = _T("center");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
}

void CMainFrame::OnUpdateNotesCenteralign(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::notesParaCenter);
}

void CMainFrame::OnNotesRightalign()
{
	CNotesPage::ActiveMainFrameCommand = _T("right");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
}

void CMainFrame::OnUpdateNotesRightalign(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::notesParaRight);
}

void CMainFrame::OnNotesInsertbullets()
{
	CNotesPage::ActiveMainFrameCommand = _T("bullets");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
}



/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// Messages from main frame to the dictionary window /////////////////////////////
void CMainFrame::OnDictionaryPrint()
{
	CBottomLeft::ActiveMainFrameCommand = _T("print");
	SendMessageToDescendants(ID_DICTIONARY_COMMAND,0,0);
	
}

void CMainFrame::OnDictionaryCopy()
{
	CBottomLeft::ActiveMainFrameCommand = _T("copy");
	SendMessageToDescendants(ID_DICTIONARY_COMMAND,0,0);

}

void CMainFrame::OnDictionarySelectall()
{
	CBottomLeft::ActiveMainFrameCommand = _T("selectall");
	SendMessageToDescendants(ID_DICTIONARY_COMMAND,0,0);
	
}

void CMainFrame::OnBottomleftDisplay()
{
	CBottomLeft::ActiveMainFrameCommand = _T("display");
	SendMessageToDescendants(ID_DICTIONARY_COMMAND,0,0);
	
}

void CMainFrame::OnDictionaryZoomtext()
{
	CBottomLeft::ActiveMainFrameCommand = _T("zoom");
	SendMessageToDescendants(ID_DICTIONARY_COMMAND,0,0);
}

void CMainFrame::OnUpdateDictionaryZoom(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::dictZoom);
}



void CMainFrame::OnDictionaryPrevious()
{
	CBottomLeft::ActiveMainFrameCommand = _T("previous");
	SendMessageToDescendants(ID_DICTIONARY_COMMAND,0,0);

}

void CMainFrame::OnDictionaryNext()
{
	CBottomLeft::ActiveMainFrameCommand = _T("next");
	SendMessageToDescendants(ID_DICTIONARY_COMMAND,0,0);
	
}

void CMainFrame::OnDictionaryInfo()
{
	CBottomLeft::ActiveMainFrameCommand = _T("info");
	SendMessageToDescendants(ID_DICTIONARY_COMMAND,0,0);
	
}


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// Messages from main frame to the General Books Window /////////////////////////////
void CMainFrame::OnGenBooksPrint()
{
	CGenBooks::ActiveMainFrameCommand = _T("print");
	SendMessageToDescendants(ID_GENBOOKS_COMMAND,0,0);
	
}

void CMainFrame::OnGenBooksCopy()
{
	CGenBooks::ActiveMainFrameCommand = _T("copy");
	SendMessageToDescendants(ID_GENBOOKS_COMMAND,0,0);

}

void CMainFrame::OnGenBooksSelectall()
{
	CGenBooks::ActiveMainFrameCommand = _T("selectall");
	SendMessageToDescendants(ID_GENBOOKS_COMMAND,0,0);
	
}

void CMainFrame::OnGenBooksDisplay()
{
	CGenBooks::ActiveMainFrameCommand = _T("display");
	SendMessageToDescendants(ID_GENBOOKS_COMMAND,0,0);
	
}

void CMainFrame::OnGenBooksZoomtext()
{
	CGenBooks::ActiveMainFrameCommand = _T("zoom");
	SendMessageToDescendants(ID_GENBOOKS_COMMAND,0,0);
}

void CMainFrame::OnUpdateGenBooksZoom(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::GenBookZoom);
}



void CMainFrame::OnGenBooksPrevious()
{
	CGenBooks::ActiveMainFrameCommand = _T("previous");
	SendMessageToDescendants(ID_GENBOOKS_COMMAND,0,0);

}

void CMainFrame::OnGenBooksNext()
{
	CGenBooks::ActiveMainFrameCommand = _T("next");
	SendMessageToDescendants(ID_GENBOOKS_COMMAND,0,0);
	
}

void CMainFrame::OnGenBooksInfo()
{
	CGenBooks::ActiveMainFrameCommand = _T("info");
	SendMessageToDescendants(ID_GENBOOKS_COMMAND,0,0);
	
}


////////////////////////////////////////////////// General Options Messages ////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void CMainFrame::OnOptionsRememberlast()
{
	CSwordBibleDoc::rememberLastVerse = !(CSwordBibleDoc::rememberLastVerse);
	
	//  store in registry
	AfxGetApp()->WriteProfileInt(_T("General Options"),_T("Remember Last"),CSwordBibleDoc::rememberLastVerse);
	
}

void CMainFrame::OnUpdateRememberlast(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::rememberLastVerse);
}

void CMainFrame::OnOptionsDevotional()
{
	 CSwordBibleDoc::devotion_startup = !(CSwordBibleDoc::devotion_startup);
	 AfxGetApp()->WriteProfileInt(_T("Devotional"),_T("Startup"),  CSwordBibleDoc::devotion_startup);
}

void CMainFrame::OnUpdateOptionsDevotional(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(CSwordBibleDoc::devotion_startup);
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void CMainFrame::OnQuickVerseGo()
{
	CString keyStr = _T("");
	QuickVerseCombo.GetWindowText(keyStr);

  if(GoToBibleVerse(keyStr) == FALSE) return;

}


void CMainFrame::AddCurrentVerseToHistory()
{
  CString verse = (CString) CSwordBibleDoc::key.getShortText(); 

  int count = CSwordBibleDoc::VerseHistory.GetCount();
  
  for(int i =0; i < count; i++) {
    if(CSwordBibleDoc::VerseHistory.GetAt(i) == verse) {
       CSwordBibleDoc::VerseHistory.RemoveAt(i);
       count--;
    }
  }

	// Add the verse to history
	CSwordBibleDoc::VerseHistory.InsertAt(0, verse);
  count++;

	
	while (count > MAXHISTORY)    // VerseHistory  full
	{
		CSwordBibleDoc::VerseHistory.RemoveAt(count - 1);
		count = CSwordBibleDoc::VerseHistory.GetCount();
	}



}

BOOL CMainFrame::GoToBibleVerse(CString& verse)
{
  if(verse.GetLength() < 2) return FALSE;
		
	
	sword::VerseKey vk;
	sword::ListKey lk = vk.ParseVerseList((CStringA) verse, vk, TRUE);
	lk = sword::TOP;
	

	if(lk.Error() || lk.Count() < 1) return FALSE;

	
	CSwordBibleDoc::key = lk.getShortText();
  verse = (CStringA) CSwordBibleDoc::key.getShortText();
	
	CBiblePage::ActiveMainFrameCommand = _T("ShowChapter");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND, 0,0);

	if(CSwordBibleDoc::notesSynch)
	{
	CNotesPage::ActiveMainFrameCommand = _T("BibleSynch");
	SendMessageToDescendants(ID_NOTES_COMMAND,0,0);
	}

	if(CSwordBibleDoc::bottomSynch)
	{
	CBottomPage::ActiveMainFrameCommand = _T("BibleSynch");
	SendMessageToDescendants(ID_COMMENTARY_COMMAND,0,0);
	}

	// highlight the verse in the bible window
	CBiblePage::ActiveMainFrameCommand = _T("highlight");
	SendMessageToDescendants(ID_BIBLEPAGE_COMMAND,0,0);

  AddCurrentVerseToHistory();		

  return TRUE;
}

void CMainFrame::OnQuickVerseDropDown()
{

  int count = CSwordBibleDoc::VerseHistory.GetCount();

   while(QuickVerseCombo.GetCount() > 0 )   //  empty the combo box
	 QuickVerseCombo.DeleteString(0);


  for(int i = 0; i < count; i++) {
    QuickVerseCombo.AddString(CSwordBibleDoc::VerseHistory.GetAt(i));
  }
}
